import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { uploadArticleCover, createArticleMeta, type ArticleMetaPayload } from '@/api/article/article'

interface PublishPayload {
  title: string
  category?: string
  description?: string
  content?: string
  status?: 'DRAFT' | 'PUBLISHED' | 'ARCHIVED'
}

export const useArticleStore = defineStore('article', {
  state: () => ({
    // 提交状态
    submitting: false,
    coverUploading: false,
    // 服务端返回的标识/地址
  coverUrl: '' as string | null | '',
    // 预览用对象URL
    coverPreviewUrl: '' as string,
    // 最近一次创建返回
    lastCreateResp: null as any,
    error: null as string | null,
  }),
  actions: {
    setCoverPreview(file: File) {
      if (this.coverPreviewUrl) URL.revokeObjectURL(this.coverPreviewUrl)
      this.coverPreviewUrl = URL.createObjectURL(file)
    },
    clearCover() {
      if (this.coverPreviewUrl) URL.revokeObjectURL(this.coverPreviewUrl)
      this.coverPreviewUrl = ''
  this.coverUrl = ''
    },
    async uploadCover(file: File) {
      this.coverUploading = true
      this.error = null
      try {
        // console.log('开始上传封面：', file)
        const resp: any = await uploadArticleCover(file)
        // console.log('封面上传响应：', resp)
        // 兼容多种返回结构
        const data = resp?.data ?? resp
        const url = data?.url ?? data?.coverUrl ?? resp?.url ?? resp?.coverUrl ?? ''
        if (!url) throw new Error('上传封面成功但未返回封面URL')
        this.coverUrl = url
        return { coverUrl: url }
            } catch (e: any) {
        this.error = e?.message || '封面上传失败'
        ElMessage.error(this.error || '封面上传失败')
        throw e
      } finally {
        this.coverUploading = false
      }
    },
    async createMeta(payload: ArticleMetaPayload) {
      this.submitting = true
      this.error = null
      try {
        const res = await createArticleMeta(payload)
        this.lastCreateResp = res
        ElMessage.success('发布成功')
        return res
      } catch (e: any) {
    this.error = e?.message || '发布失败'
    ElMessage.error(this.error || '发布失败')
        throw e
      } finally {
        this.submitting = false
      }
    },
    // 一站式发布：先上传封面，再提交元数据
    async publishArticle(meta: PublishPayload, file: File) {
      this.submitting = true
      this.error = null
      try {
        // console.log('发布文章，上传封面：', file)
        const { coverUrl } = await this.uploadCover(file)
        // console.log(coverUrl)
        const res = await this.createMeta({ coverUrl, ...meta })
        return res
      } finally {
        this.submitting = false
      }
    },
  }
})
